package com.wave.traffic.task;

import cn.hutool.core.util.NumberUtil;
import com.wave.traffic.enums.NetControllerEnum;
import com.wave.traffic.listener.InitKND;
import com.wave.traffic.util.DelayTaskUtil;
import com.wave.traffic.util.SocketClientUtil;
import com.wave.traffic.util.TimerUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class KNDRunnable implements Runnable {
    private ServerInfo serverInfo;
    private Socket socket;
    public KNDRunnable(Socket socket, ServerInfo serverInfo) {
        this.socket = socket;
        this.serverInfo = serverInfo;
    }

    @Override
    public void run() {
        try {
            //读取DI主动上报的信息
            InputStream is = socket.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] bytes = new byte[10]; // 一次读取一个byte
            String ret = "";

            //实现读功能
            Socket netController1;
            Socket netController2;
            Socket netController3;
            Map<Socket, String> map = new ConcurrentHashMap<>();
            String str;
            while (true) {
                log.info("AAAAAAAAAA");
                try {
                    bis.read(bytes);
                } catch (IOException e) {
                    log.info("康耐德下线了：" + socket.getRemoteSocketAddress());
                    InetSocketAddress remoteSocketAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
                    InitKND.socketMap.remove(remoteSocketAddress.getHostName());
                    socket.close();
                    log.info("*****康耐德列表*****");
                    log.info("康耐德总数：{}", InitKND.socketMap.size());
                    InitKND.socketMap.forEach((k, v) -> log.info("康耐德ip：{}, 康耐德socket信息：{}", k, v));
                    break;
                }
                ret += bytesToHexString(bytes) + " ";  //调用字节转化16进制字符串方法
                if (!StringUtils.isEmpty(ret)) {//有人要通行

                    netController1 = InitKND.socketMap.get(serverInfo.getServerIP1());
                    netController2 = InitKND.socketMap.get(serverInfo.getServerIP2());
                    netController3 = InitKND.socketMap.get(serverInfo.getServerIP3());

                    //获取雷视摄像头感应道路是否有车的结果
                    boolean hasCar = HKCameraTask.hasCar;
                    log.info("有人要通行,道路是否有车：" + hasCar);
                    str = ret;
                    str = str.trim();
                    String[] strs = str.split(",");
                    String lastPart = strs[strs.length - 1];
                    int lastPartInt = NumberUtil.parseInt(lastPart);
                    log.info("闸机是否有人：" + lastPartInt);
                    if ((lastPartInt == 1) && !hasCar) {
                        if(netController1 != null && netController2 != null && netController3 != null){
                            log.info("控制器打开人行绿灯,打开车辆红灯");
                            //SocketClientUtil.sendData(netController1, NetControllerEnum.WRITE_DO1_CLOSE_COMMAND.getCode());
                            map = new ConcurrentHashMap<>();
                            map.put(netController1, NetControllerEnum.WRITE_DO1_CLOSE_COMMAND.getCode());
                            HKCameraTask.blockingQueue1.put(map);

                            log.info("控制器打开人行绿灯,打开车辆红灯-213-1");
                            //SocketClientUtil.sendData(netController1, NetControllerEnum.WRITE_DO2_OPEN_COMMAND.getCode());
                            map = new ConcurrentHashMap<>();
                            map.put(netController1, NetControllerEnum.WRITE_DO2_OPEN_COMMAND.getCode());
                            HKCameraTask.blockingQueue1.put(map);

                            log.info("控制器打开人行绿灯,打开车辆红灯-213-2");
                            //剩余两个网络控制器控制的人行灯切换成绿灯
                            //SocketClientUtil.sendData(netController2, NetControllerEnum.WRITE_DO1_OPEN_COMMAND.getCode());
                            map = new ConcurrentHashMap<>();
                            map.put(netController2, NetControllerEnum.WRITE_DO1_OPEN_COMMAND.getCode());
                            HKCameraTask.blockingQueue2.put(map);

                            log.info("人行灯切换成绿灯-212");
                            //SocketClientUtil.sendData(netController3, NetControllerEnum.WRITE_DO1_OPEN_COMMAND.getCode());
                            map = new ConcurrentHashMap<>();
                            map.put(netController3, NetControllerEnum.WRITE_DO1_OPEN_COMMAND.getCode());
                            HKCameraTask.blockingQueue3.put(map);

                            log.info("人行灯切换成绿灯-215");
                            //新建20s的延时任务，20s后所有人行灯切换成红灯，交通灯切换成绿灯
                            log.info("发送延时任务");
                            TimerUtil.call(netController1, netController2, netController3, 30000L);
                            //DelayTaskUtil.execute(netController1, netController2, netController3, 30000L);
                        }
                    }
                    ret = "";
                }
            }
        } catch (Exception e) {
            log.error("netControllerTask throws exception is {}", e.getMessage(), e);
        }
    }

    private static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            stringBuilder.append("0x");

            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
            if (i != src.length - 1) {
                stringBuilder.append(",");

            }
        }
        return stringBuilder.toString();
    }

}
